<template>
  <bs-container>
    <template slot="left">
      <device-tree
        ref="deviceTree"
        :show-tabs="true"
        :query-data.sync="queryData"
        :have-data="haveData"
        @nodeClick="treeClick"
      ></device-tree>
    </template>
    <template slot="search">
      <device-condition
        :query-data="queryData"
        :selectData="!allSize && macs.length < 1"
        @layout="doLayout"
        :state-btn-disabled="doExamineDisable"
        @action="doShowCarInfo"
      ></device-condition>
    </template>
    <template slot="list">
      <x-table
        ref="list"
        showIndex
        :border="false"
        height="100%"
        :table-data="tableData"
        :show-select="showSelect"
        :list-cols="colData"
        :action-opts="actionOpts"
        :page="pageData.page"
        :limit="pageData.limit"
        @sort-change="handleSort"
        @selection-change="handleSelectionChange"
      >
        <template slot="auditStateSlot" slot-scope="{ row }">
          {{ row.auditState | auditStateFilter(te) }}
        </template>
        <template slot="actionSlot" slot-scope="{ row }">
          <el-button type="text" @click.native="handleEditClick(row)">编辑</el-button>
          <el-button type="text"
            @click.native="handleDelClick(row)"
            style="color:#F56C6C;"
            >删除</el-button>
        </template>
      </x-table>
    </template>
    <template slot="footer">
        <pagination
          :total="pageData.total"
          :page="pageData.page"
          :limit="pageData.limit"
          @pagination="doList"
          :showAllChecked="true"
          :allChecked="allSize"
          @all="handleChangeAllSize"
        ></pagination>
        <edit-device-dialog></edit-device-dialog>
        <device-examine-dialog></device-examine-dialog>
        <device-layout-dialog></device-layout-dialog>
      </template>
  </bs-container>
</template>

<script>
import DeviceTree from '../components/DeviceTree'
import List from '@/components/List'
import xxTable from '@/components/XTable'

import DeviceCondition from './components/DeviceCondition'
import EditDeviceDialog from './components/EditDeviceDialog'
import DeviceExamineDialog from './components/DeviceExamineDialog'
import DeviceLayoutDialog from './components/DeviceLayoutDialog'
import Pagination from '@/components/Pagination'
// import CommonApi from '@/api/common'
import DeviceApi from '@/api/device'
export default {
  data() {
    return {
      actionOpts: {
        show: true,
        align: 'center',
        width: '120px',
        hidEditBtn: true,
        hidDelBtn: true,
        name: '操作',
        fixed:"right",
        slot: true
      },
      pageData: {
        page: 1,
        total: 0,
        limit: 15
      },
      macs: [],
      ids: [],
      doExamineDisable: false,
      queryData: { showChild: true, queryType: 2 },
      tableData: [],
      colData: [
        { label: '设备名称', prop: 'name', minwidth: 100 },
        { label: 'MAC地址', prop: 'macText', minwidth: 125 },
        { label: '审核状态', prop: 'auditState', slot: true, minwidth: 100 },
        { label: '分组', prop: 'groupName', minwidth: 100 },
        { label: '安装城市', prop: 'cityName', minwidth: 100 },
        { label: '安装位置', prop: 'location', minwidth: 100 }
      ],
      initColsProps: [
        'name',
        'macText',
        'auditState',
        'groupName',
        'cityName',
        'location'
      ],
      tableName: 'deviceInfoTable',
      showCarInfo: false,
      showGroupEdit: false,
      exportGroupList: [], //导出所有分组数据
      showGroupDeviceEdit: false,
      editBusCompany: '',
      allSize: false
    }
  },
  mounted: function() {
    this.$nextTick(function() {
      this.doList()
    })
  },
  created() {
    this.$eventBus.$on('doList', this.doList)
    this.$eventBus.$on('doDeleteBatch', this.doDeleteBatch)
    this.$eventBus.$on('doDelete', this.doDelete)
    this.$eventBus.$on('doExamine', this.doExamine)
    this.$eventBus.$on('submitExamine', this.submitExamine)
    this.$eventBus.$on('doSet', this.doSet)
  },
  beforeDestroy() {
    this.$eventBus.$off('doList')
    this.$eventBus.$off('doDeleteBatch')
    this.$eventBus.$off('doDelete')
    this.$eventBus.$off('doExamine')
    this.$eventBus.$off('submitExamine')
    this.$eventBus.$off('doSet')
  },
  filters: {
    // 过滤到期时间
    // expiredDateFilter(e) {
    //   if (new Date().getTime() > new Date(e).getTime()) {
    //     return e
    //   }
    // },
    // // 过滤未到期时间
    // unexpiredDateFilter(e) {
    //   if (new Date().getTime() < new Date(e).getTime()) {
    //     return e
    //   }
    // },
    auditStateFilter(val, te) {
      let msg = ''
      switch (val) {
        case 0:
          msg = te('待审核')
          break
        case 1:
          msg = te('已通过')
          break
        case -1:
          msg = te('已拒绝')
          break
      }
      return msg
    }
  },
  methods: {
    initTable(config) {
      this.initHeadmuneFlag = true
    },
    // 编辑
    handleEditClick(row) {
      this.$store
        .dispatch('device/doLoadDeviceByID', { id: row.id })
        .then(res => {
          console.log('doLoadDeviceByID', res)
          if (res) {
            this.$eventBus.$emit('addDeviceDialogShow', res)
          }
        })
    },
    // 删除
    handleDelClick(row) {
      this.$eventBus.$emit('doDelete', row)
    },
    // 排序
    handleSort(sortInfo) {
      console.log('sortInfo----', sortInfo)
      switch (sortInfo.prop) {
        case 'name':
          this.queryData.orderType = 1
          break
        case 'macText':
          this.queryData.orderType = 2
          break
        case 'auditState':
          this.queryData.orderType = 3
          break
        // case 'model':
        //   this.queryData.orderType = 4
        //   break
        case 'groupName':
          this.queryData.orderType = 5
          break
        case 'cityName':
          this.queryData.orderType = 6
          break
        case 'location':
          this.queryData.orderType = 8
          break
        // case 'expiredDate':
        //   this.queryData.orderType = 7
        //   break
        default:
          this.$alert('提示', '系统不支持排序')
          return
      }
      this.queryData.orderParam = sortInfo.type
      this.doList()
    },
    // 过滤
    handleFilter(filterInfo) {
      console.log('filterInfo----', filterInfo)
      if (filterInfo) {
      }
    },
    treeClick(node) {
      const { data } = node
      this.queryData.groupId = data.id == 0 ? -2 : data.id
      this.doList({ page: 1 })
    },
    // 查询列表
    doList(current) {
      if (current) {
        this.pageData = {
          ...this.pageData,
          ...current
        }
      }
      this.allSize = false
      var queryData = this.$data.queryData
      queryData.current = this.pageData.page
      queryData.size = this.pageData.limit
      // if(queryData.groupId == 0)
      // {
      //   delete queryData.groupId
      // }
      this.$store.dispatch('device/doDeviceList', queryData).then(res => {
        if (res) {
          this.tableData = res.records ? res.records : []
          this.pageData.total = Number(res.total ? res.total : 0)
        }
      })
    },
    // 多选
    handleSelectionChange(val) {
      console.log('handleSelectionChange========', val)
      this.macs = []
      this.ids = []
      this.doExamineDisable = false
      for (let i = 0; i < val.length; i++) {
        this.macs.push(val[i].macText)
        this.ids.push(val[i].id)
        // 通过或者拒绝审核的
        if (val[i].auditState == 1 || val[i].auditState == -1) {
          this.doExamineDisable = true
        }
      }
    },
    // 批量删除
    doDeleteBatch() {
      if (!this.allSize && this.macs.length < 1) {
        this.$alert('提示', '请先选择要删除的行')
        return
      }
      this.$confirm('提示', '是否确认删除？').then(res => {
        if (res) {
          this.$message.success('删除成功')
          let params = {
            macs: this.macs,
            ids: this.ids
          }
          let queryData = {}
          if (this.allSize) {
            queryData = {
              ...this.queryData,
              queryGroupId: this.queryData.groupId,
              allSize: this.allSize,
              total: this.pageData.total
            }
            delete queryData.groupId
          }
          this.$store
            .dispatch('device/doDeleteDevice', {
              ...params,
              ...queryData
            })
            .then(res => {
              this.doList({ page: 1 })
            })
        }
      })
    },
    // 删除
    doDelete(row) {
      this.$confirm('提示', '是否确认删除？').then(res => {
        if (res) {
          this.$message.success('删除成功')
          let params = {
            macs: row.macText,
            ids: row.id
          }
          this.$store.dispatch('device/doDeleteDevice', params).then(res => {
            this.doList()
          })
        }
      })
    },
    doExamine() {
      if (this.ids.length < 1) {
        this.$alert('提示', '请先选择要审核的记录')
        return
      }
      const editorForm = {}
      this.$eventBus.$emit('showDeviceExamineDialog', editorForm)
    },
    // 审核
    submitExamine(val) {
      if (this.ids.length < 1) {
        this.$alert('提示', '请先选择要审核的记录')
        return
      }
      this.$store
        .dispatch('device/doDeviceExamine', { ids: this.ids, auditState: val })
        .then(res => {
          if (res) {
            this.doList()
          }
        })
    },
    // 设置
    doSet() {
      if (!this.allSize && this.ids.length < 1) {
        this.$alert('提示', '请先选择终端')
        return
      }
      if (this.ids.length === 1) {
        this.$store
          .dispatch('device/doLoadDeviceByID', { id: this.ids })
          .then(res => {
            if (res) {
              this.$eventBus.$emit('addDeviceDialogShow', res)
            }
          })
      } else {
        let queryData = {}
        if (this.allSize) {
          queryData = {
            ...this.queryData,
            queryGroupId: this.queryData.groupId,
            allSize: this.allSize,
            type: 1,
            total: this.pageData.total
          }
          delete queryData.groupId
        }
        this.$eventBus.$emit(
          'addDeviceDialogShow',
          { macs: this.macs, ids: this.ids },
          queryData
        )
      }
    },
    getActiveItem() {
      let items = this.$refs.list.getActiveItem()
      return items.length === 1 ? items[0] : items.length === 0 ? {} : items
    },
    // 终端布局
    doLayout() {
      if (!this.allSize && this.macs.length < 1) {
        this.$alert('提示', '请先选择终端')
        return
      }
      const param = this.getActiveItem()
      if (!param.width || param.width === 0) {
        param.width = 4000
      }
      if (!param.height || param.height === 0) {
        param.height = 4000
      }
      let queryData = {}
      if (this.allSize) {
        queryData = {
          ...this.queryData,
          allSize: this.allSize,
          total: this.pageData.total
        }
      }
      this.$eventBus.$emit('showDeviceLayoutDialog', param, queryData)
    },

    te(arg) {
      const hasKey = this.$te(arg)
      if (hasKey) {
        const result = this.$t(arg)
        return result
      }
      return arg
    },

    doShowCarInfo() {
      this.showCarInfo = true
    },
    // 选择所有页
    handleChangeAllSize(val) {
      this.doExamineDisable = val
      this.allSize = val
      this.$refs.list.clearSelection()
    },
    doShowGroupEdit(data) {
      // this.loadCarInfo()
      console.log('doShowGroupEdit========', data)
      this.exportGroupList = data.busCompanys.map(item => {
        let group = {
          groupName: item
        }
        return group
      })
      this.showGroupEdit = true
    },
    doGroupDeviceEdit(group) {
      this.editBusCompany = group.groupName
      this.showGroupDeviceEdit = true
    },
    // async loadCarInfo() {
    //   var queryData = {}
    //   //  queryData.current = 1
    //   // queryData.size = 15
    //   const res = await DeviceApi.loadCarInfo(queryData)
    //   if (res && res.records) {
    //     this.editDevices = res.records

    //     this.exportGroupList = []
    //     this.exportGroupList = this.groupUnique(groups)
    //   }
    // },
    async doExportConfirm() {
      const res = await DeviceApi.updateGroupConfirm({})
      if (res) {
        this.showGroupEdit = false
        this.$refs.carInfo.refreshCarInfo()
        this.$refs.deviceTree.refreshNode()
        this.doList({ page: 1 })
      }
    },
    //数组去重
    groupUnique(arr) {
      let result = []
      arr.forEach(element => {
        if (
          result.findIndex(item => item.groupName == element.groupName) == -1
        ) {
          result.push(element)
        }
      })
      return result
    }
  },
  computed: {
    haveData() {
      return this.tableData.length > 0
    },
    // 是否有批量操作
    showSelect(){
      let i = this.$_has('TERMINAL_TERMINAL_DELETE') || this.$_has('TERMINAL_TERMINAL_UPDATE')
      return i
    },
  },
  components: {
    DeviceCondition,
    DeviceTree,
    List,
    EditDeviceDialog,
    DeviceExamineDialog,
    DeviceLayoutDialog,
    Pagination,
    xxTable
  }
}
</script>
<style lang="scss" scoped>
.edit {
  color: $bg-33;
}
</style>

<style lang="scss" scoped>
.leftMain {
  // ::v-deep .el-tree>.el-tree-node {
  //   min-width:100%;
  //   height: calc(100vh - 211px);
  //   display:inline-block;
  // }
  // ::v-deep .tree{width: 100%; height: 100%; overflow-x: scroll;}
  ::v-deep .el-tree-node {
    position: relative;
    // padding-left: 10px;
  }
}
</style>
